package com.tedu.dao.impl;

import com.tedu.dao.StudentDao;
import com.tedu.entity.Student;
import com.tedu.utils.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StudentDaoImpl implements StudentDao {
    @Override
    public void insertStudent(Student student) {
        Connection conn = null;
        PreparedStatement pstm = null;
        //加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");

            //url
            String url = "jdbc:mysql://localhost:3306/xianyangshifan?characterEncoding=utf-8";
            String username = "root";
            String password = "root";

        //获取链接
            conn = DriverManager.getConnection(url,username,password);
            String sql = "insert into student(name,pass,birthday) value(?,?,?)";
        //创建PrepareStatement语句
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, "杨延喆");
            pstm.setString(2, "521521");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date utilDate= sdf.parse("1998-5-20");
            java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
            pstm.setDate(3, sqlDate);
            //执行sql
            boolean b = pstm.execute();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if(pstm != null){
                try {
                    pstm.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

    }

    @Override
    public void dbUtisInsertStudent(Student student) throws SQLException {
        Connection conn = DataSource.getConnection();

        QueryRunner qr = new QueryRunner();
        Object[] params= {student.getName(),student.getPass(),student.getBirthday()};
        qr.update(conn,"insert into student(name,pass,birthday) value(?,?,?)",params);
        DbUtils.close(conn);

    }
}
